<script setup lang="ts">
  import { ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { ApiMemberPhoneSms } from '~/apis'
import excludedIcon from '/images/webp/setting/excluded_icon.webp'

  const { t } = useI18n()

  definePageMeta({
    layout: 'header-back',
    title: 'self_exclusion'
  })
  const appStore = useAppStore()
  const { userInfo } = storeToRefs(appStore)
  const area = ref('')
  const phone = ref('')
  const email = ref('')
  console.log('userInfo', userInfo.value)
  // 是否显示验证码弹框
  const showVerifyModal = ref(false)
  // 倒计时
  const countdown = ref(0)
  // 是否已发送验证码
  const codeSent = ref(false)
  // 是否显示倒计时
  const showCountdown = ref(false)
  // 倒计时定时器
  let countdownTimer: number | null = null
  // 验证码
  const verifyCode = ref('')
  // 验证码是否发生变化
  const isVerifyCodeChanged = ref(false)
  // 是否显示中间的弹框
  const isBaseDialogShow = ref(false) // 初始为未排除，可根据实际状态调整
  const countDown = ref(60)
  const captcha = ref('')
  const step = ref(1)
  const exclude = computed(() => {
    return userInfo.value?.exclude === 1
  })
  const isExcludeShow = ref(false) // 初始为未排除，可根据实际状态调整
  // 显示处于什么状态
  const spet = ref(1) // 1:未排除，2:解除排除

  const useCaptcha = computed(() => {
    if (userInfo.value?.phone) return 'phone'
    if (userInfo.value?.email) return 'email'
    return ''
  })
  // 是否已启动自我排除
  const isExclusionActive = ref(false) // 初始为未排除，可根据实际状态调整

  // 请求自我排除
  const requestExclusion = () => {
    isBaseDialogShow.value = true
  }

  // 解除自我排除
  const cancelExclusion = () => {
    // message.success(t('self_exclusion_deactivated'))
    isBaseDialogShow.value = true
  }
  function sendCode() {
    if (step.value === 1) showVerifyModal.value = true
    else isExcludeShow.value = true
    // const callback = () => {
    //   step.value = 2
    // }

    // if (useCaptcha.value === 'email')
    //   ApiExcludeSendMailCode({ email: userInfo.value!.email }).then(callback)
    // else
    //   ApiMemberPhoneSms({ type: 1, uid: userInfo.value!.uid }).then(callback)
  }
  function submit(ty: number) {
    //ty  1=邮箱验证，2=手机验证，3=无验证
    // 验证成功后关闭弹窗
    showVerifyModal.value = false
    verifyCode.value = ''
    isExclusionActive.value = !isExclusionActive.value
    isBaseDialogShow.value = false
    isExcludeShow.value = false
    if (!exclude.value) step.value = 2
    else step.value = 1
    message.success(`${!exclude.value ? t('extend_on_content') : t('extend_off_content')}`)
    // memberExclude({ ty, captcha: captcha.value, exclude: !exclude.value ? 1 : 2 }).then(() => {
    //   appStore.updateUserInfo().then(() => {
    //     // 验证成功后关闭弹窗
    //     showVerifyModal.value = false
    //     verifyCode.value = ''
    //     isExclusionActive.value = true
    //     isBaseDialogShow.value = false
    //     message.success(`${exclude.value ? t('extend_on_content') : t('extend_off_content')}`)
    //   })
    // })
  }
  //验证码
  /** 发送手机验证码 */
  const { runAsync: runAsyncSendPhoneSms } = useRequest(ApiMemberPhoneSms, {
    onSuccess() {
      message.success(`${t('success_send_code')}`)
    }
  })
  /** 发送邮箱验证码 */
  const { runAsync: runAsyncSendEmailSms } = useRequest(ApiExcludeSendMailCode, {
    onSuccess() {
      message.success(`${t('success_send_code')}`)
    }
  })
  // 发送验证码
  const sendVerifyCode = async () => {
    // 组合区号和手机号
    const fullPhoneNumber = userInfo.value?.phone
    try {
      if (userInfo.value?.exclude === 1) {
        runAsyncSendEmailSms({ email: userInfo.value!.email })
        isExcludeShow.value = true
      } else {
        runAsyncSendPhoneSms({ type: 1, uid: userInfo.value!.uid })
        showVerifyModal.value = true
      }
      // 标记验证码已发送
      codeSent.value = true
      startCountdown()
    } catch (error) {
      message.error(t('send_code_failed'))
    }
  }
  // 重新发送验证码
  const resendVerifyCode = () => {
    if (countdown.value > 0) return
    // 重新发送验证码
    sendVerifyCode()
  }
  // 开始倒计时
  const startCountdown = () => {
    showCountdown.value = true
    countdown.value = 57 // 57秒倒计时
    if (countdownTimer) {
      clearInterval(countdownTimer)
    }
    countdownTimer = window.setInterval(() => {
      if (countdown.value > 0) {
        countdown.value--
      } else {
        if (countdownTimer) {
          clearInterval(countdownTimer)
          countdownTimer = null
          showCountdown.value = false
        }
      }
    }, 1000)
  }
  // 关闭验证码弹框
  const closeVerifyModal = () => {
    showVerifyModal.value = false
    isExcludeShow.value = false
    verifyCode.value = ''
    // 不重置codeSent，保持状态，以便下次打开时仍显示"再次发送"
  }
  // 提交验证码
  const submitVerifyCode = (ty: number) => {
    captcha.value = verifyCode.value
    submit(ty)
    // 验证码验证逻辑
    console.log('提交验证码:', verifyCode.value)
  }
  // 监听验证码变化
  watch(
    () => verifyCode.value,
    newVal => {
      isVerifyCodeChanged.value = newVal !== ''
    },
    { deep: true, immediate: true }
  )
  onMounted(() => {
    if (userInfo.value?.phone) {
      area.value = userInfo.value?.phone.split('-')[0]
      phone.value = userInfo.value?.phone.split('-')[1]
    }
    if (userInfo.value?.email) {
      const [localPart, domain] = userInfo.value.email.split('@')
      const prefix = localPart.slice(0, 3)
      const suffix = localPart.slice(-3)
      const maskedPart = '*'.repeat(localPart.length - 6)
      email.value = `${prefix}${maskedPart}${suffix}@${domain}`
    }
    // 重置验证码相关状态
    showCountdown.value = false
    countdown.value = 0
    codeSent.value = false
    if (countdownTimer) {
      clearInterval(countdownTimer)
      countdownTimer = null
    }
  })
</script>

<template>
  <div class="exclusion-page">
    <div class="exclusion-content">
      <!-- 页面标题 -->
      <div class="page-title">{{ t('self_exclusion') }}</div>

      <!-- 自我排除部分 -->
      <div class="section">
        <div class="section-item">
          <div class="content">
            <!-- 标题和图标 -->
            <BaseImage width="28px" style="height: 28px; margin-bottom: 10px" :url="excludedIcon" />
            <div class="title">{{ t('self_exclusion') }}</div>

            <!-- 未激活状态文本 -->
            <div v-if="!isExclusionActive" class="description-text">
              <p class="description-text-title">{{ t('self_exclusion_need_rest') }}</p>
              <p>{{ t('self_exclusion_description') }}</p>
            </div>

            <!-- 已激活状态文本 -->
            <div v-else class="description-text">
              <p style="color: #fff">{{ t('self_exclusion_rested') }}</p>
            </div>

            <!-- 操作按钮 -->
            <div class="button-row">
              <button
                v-if="!isExclusionActive"
                class="action-btn request-btn"
                @click="requestExclusion"
              >
                {{ t('self_exclusion_request') }}
              </button>
              <button v-else class="action-btn cancel-btn" @click="cancelExclusion">
                {{ t('self_exclusion_cancel') }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 中间弹框 -->
    <BaseDialog
      :show="isBaseDialogShow"
      :iconPosition="'right'"
      :title="step === -1 ? t('no_sms') : t('say_hello', { name: userInfo?.username || '' })"
    >
      <div class="flex flex-col justify-between gap-2.5">
        <div class="line flex flex-col gap-2.5" />
        <div class="flex justify-center font-bold base-title">
          {{ t(!isExclusionActive ? 'extend_content_3' : 'extend_content_9') }}
        </div>
        <span class="text light py-5">{{
          t(!exclude ? 'extend_content_4' : 'extend_content_10')
        }}</span>
        <BaseButton bg-style="secondary" size="xl" class="w-full" @click="sendCode">
          {{ t(!isExclusionActive ? 'extend_btn_2' : 'extend_btn_off') }}
        </BaseButton>
        <div class="text flex items-center justify-center py-2 bg border-solid base-text">
          <BaseIcon name="info" /> {{ t('extend_content_5') }}
        </div>
      </div>
    </BaseDialog>
    <!-- 电话验证弹框 -->
    <div v-if="showVerifyModal" class="modal-overlay" @click.self="closeVerifyModal">
      <div class="verify-modal">
        <div class="modal-header">
          <div class="modal-title">{{ t('contact_phone_verification') }}</div>
          <div class="close-btn" @click="closeVerifyModal">×</div>
        </div>
        <div class="modal-body">
          <div class="verify-instructions">
            {{ t('pls_input_verify_code_text', { area, phone }) }}
          </div>
          <div class="verify-phone">{{ t('change_password_fund') }} <span>*</span></div>
          <div class="verify-input-container">
            <input
              type="text"
              :placeholder="t('verify_code')"
              maxlength="6"
              v-model="verifyCode"
              pattern="[0-9]*"
              inputmode="numeric"
              class="code-input"
            />
            <button
              :class="[
                'code-btn',
                {
                  'resend-code-btn': showCountdown,
                  'get-code-btn': !showCountdown && !codeSent,
                  'countdown-end': countdown === 0 && !showCountdown
                }
              ]"
              :disabled="showCountdown"
              @click="resendVerifyCode"
            >
              <template v-if="showCountdown"
                >{{ countdown }}{{ t('contact_seconds_resend') }}</template
              >
              <template v-else-if="codeSent">{{ t('resend') }}</template>
              <template v-else>{{ t('get_code') }}</template>
            </button>
          </div>
          <div class="verify-actions">
            <button
              class="submit-btn"
              @click="submitVerifyCode(useCaptcha == 'email' ? 1 : 2)"
              :disabled="!isVerifyCodeChanged"
            >
              {{ t('submit') }}
            </button>
          </div>
        </div>
      </div>
    </div>
    <!-- 解除锁定 邮箱-->
    <div v-if="isExcludeShow" class="modal-overlay" @click.self="closeVerifyModal">
      <div class="verify-modal">
        <div class="modal-header">
          <div class="modal-title">{{ t('resolve_locked') }}</div>
          <div class="close-btn" @click="closeVerifyModal">×</div>
        </div>
        <div class="modal-body">
          <div class="verify-instructions">
            {{ t('pls_input_verify_code_email', { email }) }}
          </div>
          <div class="verify-input-container">
            <input
              type="text"
              :placeholder="t('verify_code')"
              maxlength="6"
              v-model="verifyCode"
              pattern="[0-9]*"
              inputmode="numeric"
              class="code-input"
            />
            <button
              :class="[
                'code-btn',
                {
                  'resend-code-btn': showCountdown,
                  'get-code-btn': !showCountdown && !codeSent,
                  'countdown-end': countdown === 0 && !showCountdown
                }
              ]"
              :disabled="showCountdown"
              @click="resendVerifyCode"
            >
              <template v-if="showCountdown"
                >{{ countdown }}{{ t('contact_seconds_resend') }}</template
              >
              <template v-else-if="codeSent">{{ t('resend') }}</template>
              <template v-else>{{ t('get_code') }}</template>
            </button>
          </div>
          <div class="account_long_time">
            {{ t('your_account_long_time_no_login') }}
          </div>
          <div class="verify-actions">
            <button
              class="submit-btn"
              @click="submitVerifyCode(useCaptcha == 'email' ? 1 : 2)"
              :disabled="!isVerifyCodeChanged"
            >
              {{ t('submit') }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
  .exclusion-page {
    height: 94vh;
    background-color: #232626;
    color: #fff;
    overflow-y: auto;
    padding: 16px;

    .page-title {
      font-size: 14px;
      font-weight: 500;
      padding: 10px 10px 15px 0;
      color: #fff;
      border-bottom: 1px solid var(--white-10010, #ffffff1a);
      margin-left: 10px;
    }

    .exclusion-content {
      background-color: #323738;
      border-radius: 8px;
    }

    .section {
      padding: 16px;
      border-bottom: 1px solid rgba(255, 255, 255, 0.1);
      padding-left: 20px;
      margin-left: 10px;
      padding-bottom: 45px;

      &:last-child {
        border-bottom: none;
      }
    }

    .section-item {
      display: flex;
      align-items: flex-start;
      gap: 16px;

      .content {
        flex: 1;

        .title {
          font-size: 16px;
          font-weight: 500;
          margin-bottom: 16px;
          border-bottom: 1px solid var(--white-10010, #ffffff1a);
          padding-bottom: 14px;
        }

        .description-text-title {
          color: #fff;
          margin-top: 30px;
        }

        .description-text {
          font-size: 12px;
          color: #b3bec1;
          margin-bottom: 20px;
          line-height: 1.5;

          p {
            margin-bottom: 12px;
          }
        }

        .button-row {
          display: flex;
          gap: 8px;
          margin-top: 30px;

          .action-btn {
            flex: 1;
            height: 40px;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
          }

          .request-btn {
            background: linear-gradient(90deg, #24ee89 0%, #9fe871 100%);

            color: #000;
          }

          .cancel-btn {
            background: linear-gradient(90deg, #24ee89 0%, #9fe871 100%);
            color: #000;
          }
        }
      }
    }

    .active-status {
      display: flex;
      align-items: center;
      justify-content: space-between;
      background-color: #292d2e;
      border-radius: 6px;
      padding: 10px 16px;
      margin-bottom: 16px;
      border: 1px solid #3a4142;

      .status-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 20px;
        height: 20px;
        background-color: #24ee89;
        border-radius: 50%;

        .check-icon {
          display: inline-block;
          width: 12px;
          height: 12px;
          background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='14' height='14' viewBox='0 0 24 24' fill='none' stroke='%23000000' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='20 6 9 17 4 12'%3E%3C/polyline%3E%3C/svg%3E");
          background-repeat: no-repeat;
          background-position: center;
          background-size: contain;
        }
      }

      .status-text {
        flex: 1;
        font-size: 12px;
        font-weight: 400;
        margin-left: 12px;
        color: #fff;
      }

      .toggle-switch {
        width: 36px;
        height: 20px;
        position: relative;
        cursor: pointer;

        .switch-track {
          width: 100%;
          height: 100%;
          border-radius: 10px;
          background-color: #3a4142;
          position: relative;

          &.active {
            background: linear-gradient(90deg, #24ee89, #9fe871);

            &:after {
              left: calc(100% - 16px);
            }
          }

          &:after {
            content: '';
            position: absolute;
            width: 14px;
            height: 14px;
            border-radius: 50%;
            background-color: #fff;
            top: 3px;
            left: 3px;
            transition: left 0.3s;
          }
        }
      }
    }
    .base-text {
      border-radius: 4px;
      background: var(---bg-black-3292D2E, #292d2e);
      border: 1px dashed var(--white-10010, #ffffff1a);
      color: var(---text-white-2B3BEC1, #b3bec1);
    }
    .base-title {
      line-height: 100%;
      width: 100%;
      font-size: 16px;
    }
  }
  :deep(.bc-dialog-container) {
    & > div:first-child {
      font-family: SF Pro;
      font-weight: 590;
      font-size: 14px;
      line-height: 100%;
      height: 29px;
      border-bottom-width: 1px;
      padding-bottom: 12px;
      gap: 0px;
      border-bottom: 1px solid var(--white-10010, #ffffff1a);
    }
  }
  :deep(.bc-dialog-wrapper .bc-dialog-container) {
    height: auto;
    max-height: 100%;
  }
  /* 弹框样式 */
  .modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: flex-end;
    z-index: 103;
  }
  .verify-modal,
  .no-code-modal {
    width: 100%;
    background-color: #232626;
    border-radius: 12px 12px 0 0;
    overflow: hidden;
    animation: slideUp 0.3s ease-out;
  }
  .modal-header {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 16px;
    position: relative;
  }
  .modal-title {
    font-size: 16px;
    font-weight: 500;
  }
  .close-btn {
    position: absolute;
    right: 16px;
    top: 50%;
    transform: translateY(-50%);
    width: 28px;
    height: 28px;
    background-color: #4a5354;
    border-radius: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
  }
  .modal-body {
    padding: 20px 16px;
  }
  /* 验证码弹框样式 */
  .verify-instructions {
    text-align: left;
    font-size: 12px;
    margin-bottom: 10px;
  }
  .account_long_time {
    text-align: center;
    font-size: 12px;
    margin-bottom: 10px;
    font-family: SF Pro;
    font-weight: 700;
    line-height: 18px;
    letter-spacing: 0%;
    vertical-align: middle;
    color: var(---text-white-2B3BEC1, #b3bec1);
  }
  .verify-phone {
    text-align: left;
    font-size: 12px;
    font-weight: 500;
    margin-bottom: 20px;
    color: var(---text-white-2B3BEC1, #b3bec1);

    span {
      font-family: SF Pro;
      font-weight: 700;
      font-size: 12px;
      line-height: 12px;
      letter-spacing: 0%;
      vertical-align: middle;
      color: var(---function-redFC3C3C, #fc3c3c);
    }
  }
  .verify-input-container {
    display: flex;
    border: 2px solid var(---border-black-33B4041, #3b4041);
    border-radius: 6px;
    background-color: #292d2e;
    height: 42px;
    margin-bottom: 20px;
    overflow: hidden;
    padding: 4px;
  }
  .code-input {
    flex: 1;
    height: 100%;
    background-color: transparent;
    border: none;
    color: white;
    font-size: 16px;
    text-align: left;
    padding: 0 8px;
    outline: none;

    &::placeholder {
      color: #b3bec1;
    }
  }
  .verify-actions {
    margin-bottom: 15px;
  }
  .no-code-link {
    text-align: left;
    a {
      color: #24ee89;
      font-size: 14px;
      text-decoration: none;
    }
  }
  .submit-btn {
    width: 100%;
    height: 46px;
    background: linear-gradient(90deg, #24ee89, #9fe871);
    color: #000;
    border: none;
    border-radius: 6px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    &:disabled {
      opacity: 0.7;
    }
  }
  .resend-code-btn {
    min-width: 110px;
    height: 100%;
    border: none;
    background-color: #3a4142;
    color: #ffffff;
    font-weight: 600;
    font-size: 14px;
    padding: 0 12px;
    white-space: nowrap;
    border-left: 1px solid #3b4041;
    border-radius: 6px;
    cursor: pointer;

    &:disabled {
      color: rgba(255, 255, 255, 0.4);
      cursor: not-allowed;
    }
  }

  .get-code-btn {
    min-width: 110px;
    height: 100%;
    border: none;
    background: linear-gradient(90deg, #24ee89, #9fe871);
    color: #000;
    font-weight: 600;
    font-size: 14px;
    padding: 0 12px;
    white-space: nowrap;
    border-left: 1px solid #3b4041;
    border-radius: 6px;
    cursor: pointer;

    &:disabled {
      opacity: 0.7;
      cursor: not-allowed;
    }
  }

  .code-btn {
    text-align: center;

    &.countdown-end {
      width: 72px;
      height: 32px;
      border-radius: 8px;
      text-align: center;
      height: 100%;
      border: none;
      background: linear-gradient(90deg, #24ee89, #9fe871);
      color: #000;
      font-weight: 600;
      font-size: 14px;
      padding: 0 8px;
      white-space: nowrap;
      border-left: 1px solid #3b4041;
      cursor: pointer;
      &:hover {
        opacity: 0.9;
      }
    }
  }
</style>
